package com.abing.core.utils;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.TriggerBuilder;

import java.util.Date;

public class CronUtil {
	
	//上次执行时间
	public static Date getPrevTriggerTime(String cron){
		if(!CronExpression.isValidExpression(cron)){
			return null;
		}
		CronTrigger trigger=getCronTrigger(cron);
		Date time0 = trigger.getStartTime();
		Date time1 = trigger.getFireTimeAfter(time0);
		Date time2 = trigger.getFireTimeAfter(time1);
		Date time3 = trigger.getFireTimeAfter(time2);
		long l = time1.getTime() -(time3.getTime() -time2.getTime());
		Date date = new Date(l);
		return date;
    }
    //获取下次执行时间（getFireTimeAfter，也可以下下次...）
	public static Date getNextTriggerTime(String cron){
		if(!CronExpression.isValidExpression(cron)){
			return null;
		}
		CronTrigger trigger=getCronTrigger(cron);
		Date time0 = trigger.getStartTime();
		Date time1 = trigger.getFireTimeAfter(time0);
		return time1;
    }

    private static CronTrigger getCronTrigger(String cron){
		CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("Caclulate Date").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
		return trigger;
	}
	public static void main(String[] args) {
		System.out.println(getPrevTriggerTime("0/2 * * * * ?"));
		System.out.println(getNextTriggerTime("0/2 * * * * ?"));
	}
}

